package br.com.minhasfinancas.web.bean;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import br.com.minhasfinancas.api.manager.UsuarioManager;
import br.com.minhasfinancas.api.model.Usuario;
import br.com.minhasfinancas.fw.bean.AbstractManagedBean;
import br.com.minhasfinancas.util.ControleSessao;

@ManagedBean
@ViewScoped
public class LoginBean extends
		AbstractManagedBean<Usuario, Long, UsuarioManager> {
	private static final long serialVersionUID = 1L;

	@Inject
	UsuarioManager usuarioManager;
	
	@Inject
	ControleSessao controleSessao;

	private String senha;
	
	private String login;

	@Override
	public String getEditView() {
		return "/cadastro.xhtml?faces-redirect=true";
	}

	@Override
	public String getListView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Usuario> handleResultList() {
		// TODO Auto-generated method stub
		return null;
	}

	public String login() {
		String retorno = null;
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpSession session = (HttpSession)ec.getSession(false);
		Usuario usuario = usuarioManager.logar(login, senha);
		
		if(usuario != null)
		{
			session.setAttribute("nomeUsuario", usuario.getNome());
			controleSessao.setNomeUsuario(usuario.getNome());
			controleSessao.setIdUsuario(usuario.getId());
		
			
			retorno = "/index.xhtml?faces-redirect=true";
		}
		
		return retorno;
	}
	
	
	public String logout() {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpSession session = (HttpSession) ec.getSession(false);
		session.removeAttribute("nomeUsuario");
		session.invalidate();
		fc.getExternalContext().getSessionMap().remove("#{UsuarioBean}");

		return "/login.xhtml?faces-redirect=true";

	}

	public String getSenha() {
		return senha;
	}

	public void setSenha(String senha) {
		this.senha = senha;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

}
